import React, {useEffect, useState} from 'react'
import { useNavigate } from 'react-router-dom'
import { Card, Ellipsis, Dialog } from 'antd-mobile'
import { AddOutline } from 'antd-mobile-icons'
import { getBlog, deleteBlog, search } from '../../api';
import Bottom from '../../components/Bottom';
import Search from '../../components/Search';
import './index.css'

export default function Blog() {
  const navigate = useNavigate()
  const [ blogList, setblogList ] = useState([])
  // const [ value, setValue ] = useState([])
  function edit() {
    navigate("/publish")
  }

  useEffect(()=>{
    blogData()
  },[])

  const onClick = (id) => {
    navigate(`/publish?id=${id}`)
  }

  async function blogData() {
    const blogList = await getBlog()
    setblogList([...blogList])
  }

  const getValue= async(value)=>{
    const result = await search({value})
    setblogList([...result])
  }

  const blogListHtml = blogList.map((blogObj)=>{
    return  <Card className='card' key={blogObj.id}>
              <div onClick={()=> onClick(blogObj.id)}><Ellipsis className='title' direction='end' rows={2} content={blogObj.title} /></div>
              
              <span>{blogObj.date}</span> 
              <span className='delete' 
                onClick={async () => {
                const result = await Dialog.confirm({
                  content: '你确定要删除吗',
                })
                if (result) {
                  try {
                    await deleteBlog({id:blogObj.id})
                    blogData()
                  } catch (error) {
                    if(error.code === 451){
                      setTimeout(() => {
                        navigate('/login')
                      }, 2000);
                    }
                  }
                  
                }
              }}>
                删除
              </span>
            </Card> 
    // return <List.Item onClick={() => blogD(blogObj.id)} key={blogObj.id}>{blogObj.id}&nbsp;&nbsp;&nbsp;{blogObj.title}</List.Item>
  })


  return (
    <div id='blog'>
      <Search getValue={getValue} />
      <div className='blog_list'>
        {blogListHtml}
      </div>
        
      <div className='add-blog' onClick={edit}>
        <AddOutline className='add' />
      </div>
      <Bottom />
    </div>
  )
}
